package com.ruoyi.pay.utils;


import com.baidu.aip.ocr.AipOcr;
import com.ruoyi.common.config.BaiduOcrApiConfig;
import com.ruoyi.pay.common.PayConstant;
import com.ruoyi.pay.domain.Qrcode;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.HashMap;

public class BaiduOcrApiClient {
    //链接超时时间 毫秒
    private static final int CONNECTION_TIMEOUT = 2000;
    //响应超时时间 毫秒
    private static final int SOCKET_TIMEOUT = 5000;

    /**
     * 获取付款码内容
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static Qrcode basicGeneral(InputStream inputStream) throws Exception {
        Qrcode qrcode = null;
        // 调用接口
        byte[] file = inputStream2byte(inputStream);
        AipOcr aipOcr = getInstance();
        JSONObject res = aipOcr.basicGeneral(file, new HashMap<String, String>());
        //System.out.println(res.toString(2));
        if(res.has("error_code"))
        {
            throw new Exception(res.getString("error_msg"));
        }
        JSONArray resultArray = res.getJSONArray("words_result");
        if(resultArray.length() > 0)
        {
            qrcode = new Qrcode();
            for (Object o : resultArray)
            {
                JSONObject jsonObject = (JSONObject)o;
                if(jsonObject.has("words"))
                {
                    String words = jsonObject.getString("words");
                    if(words.contains("支付宝"))
                    {
                        qrcode.setQrType(PayConstant.QRCODE_TYPE.QRCODE_ZFB);
                    }else if(words.contains("微信"))
                    {
                        qrcode.setQrType(PayConstant.QRCODE_TYPE.QRCODE_WX);
                    }
                    if(words.startsWith("￥"))
                    {
                        String money = words.substring(1);
                        qrcode.setQrPrice(new BigDecimal(money).multiply(new BigDecimal("100")).longValue());
                    }
                }
            }
            String qrContent = getQrCodeContent(aipOcr,file);
            qrcode.setQrContent(qrContent);
        }
        return qrcode;
    }
    /**
     * 获取付款码内容
     * @param path
     * @return
     * @throws Exception
     */
   /* public static String getQrCodeContent(String path) throws Exception {
        // 调用接口
        return getQrCodeContent(new FileInputStream(path));
    }*/
    /**
     * 获取付款码内容
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static String getQrCodeContent(InputStream inputStream) throws Exception {
        byte[] file = inputStream2byte(inputStream);
        return getQrCodeContent(null,file);
    }

    public static String getQrCodeContent(AipOcr client,byte[] bytes) throws Exception {

        if(client == null)
        {
            client = getInstance();
        }
        JSONObject res = client.qrcode(bytes, new HashMap<String, String>());
        if(res.has("error_code"))
        {
            throw new Exception(res.getString("error_msg"));
        }
        //System.out.println(res.toString(2));
        JSONObject text = res.getJSONArray("codes_result").getJSONObject(0);
        JSONArray jsonArray = text.getJSONArray("text");
        return jsonArray.get(0).toString();
    }

    private static AipOcr getInstance()
    {
        // 初始化一个AipOcr
       AipOcr client = new AipOcr(BaiduOcrApiConfig.getAppId(),
                BaiduOcrApiConfig.getApiKey(),
                BaiduOcrApiConfig.getSecretKey());
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(CONNECTION_TIMEOUT);
        client.setSocketTimeoutInMillis(SOCKET_TIMEOUT);
        return client;
    }
    private static AipOcr getInstanceLocal()
    {
        // 初始化一个AipOcr
       AipOcr client = new AipOcr("23673780",
                "53M9g3uWw6f4llIwPmnIGL5O",
                "ZZ7zZzsSX9FGjPWfsufs5ptzuOpyG5RQ");
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(CONNECTION_TIMEOUT);
        client.setSocketTimeoutInMillis(SOCKET_TIMEOUT);
        return client;
    }

    /**
     * 功能描述:
     *
     * @param inputStream 输入流
     * @return byte[] 数组
     * @author zhanghb
     * @date 2019/3/28 16:03
     * @version 1.0
     */
    public static byte[] inputStream2byte(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inputStream.read(buff, 0, 100)) > 0) {
            byteArrayOutputStream.write(buff, 0, rc);
        }
        return byteArrayOutputStream.toByteArray();
    }

    public static void main(String[] args) throws Exception {


    }
}
